package com.qiche.service.impl;

import java.util.List;

import javax.annotation.Resource;

import com.qiche.model.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qiche.aspect.Result;
import com.qiche.mapper.MerchantMapper;
import com.qiche.mapper.RegionMapper;
import com.qiche.model.Merchant;
import com.qiche.model.Region;
import com.qiche.requestpram.MemberHomePageURL;
import com.qiche.service.MerchantService;

import tk.mybatis.mapper.entity.Example;

/**
 * Created by Linzw on 2018/01/24.
 */
@Service("merchantService")
public class MerchantServiceImpl extends BaseService<Merchant> implements MerchantService {
    @Resource
    private RegionMapper regionMapper;

    @Resource
    private MerchantMapper merchantMapper;


    @Override
    public PageInfo<Merchant> selectByPage(Merchant merchant, int page, int limit) {
        //int page = start / length + 1;
        Example example = new Example(Merchant.class);
        Example.Criteria criteria = example.createCriteria();
        if (merchant.getAgentId()!=null) {
            criteria.andEqualTo("agentId", merchant.getAgentId());
        }
        if (StringUtils.isNotBlank(merchant.getName())) {
            criteria.andLike("name", "%" + merchant.getName() + "%");
        }
        if (StringUtils.isNotBlank(merchant.getPhone())) {
            criteria.andLike("phone", "%" + merchant.getPhone() + "%");
        }
        if (merchant.getStatus() != null) {
            criteria.andEqualTo("status", merchant.getStatus());
        }
        example.setOrderByClause("create_time desc");
        // 分页查询
        PageHelper.startPage(page, limit);
        List<Merchant> merchantList = selectByExample(example);
        return new PageInfo<>(merchantList);
    }

    @Override
    public Merchant selectById(Long merchantId) {
        Example example = new Example(Merchant.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("id", merchantId);
        List<Merchant> userList = selectByExample(example);
        if (userList.size() > 0) {
            return userList.get(0);
        }
        return null;
    }

    @Override
    public Merchant selectByName(String merchantName) {
        Example example = new Example(Merchant.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("name", merchantName);
        List<Merchant> userList = selectByExample(example);
        if (userList.size() > 0) {
            return userList.get(0);
        }
        return null;
    }
    
    @Override
    public Merchant selectByOfficialAccount(String officialAccount) {
        Example example = new Example(Merchant.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("officialAccount", officialAccount);
        List<Merchant> userList = selectByExample(example);
        if (userList.size() > 0) {
            return userList.get(0);
        }
        return null;
    }

    @Override
    public List<Merchant> selectByMemberHomePageURL(MemberHomePageURL memberHomePageURL) {
        return merchantMapper.selectByMemberHomePageURL(memberHomePageURL);
    }

	/*
     * @Override public Merchant selectByUsername(String username) { Example example
	 * = new Example(Merchant.class); Example.Criteria criteria =
	 * example.createCriteria(); criteria.andEqualTo("id",merchantId);
	 * List<Merchant> userList = selectByExample(example); if(userList.size()>0){
	 * return userList.get(0); } return null; }
	 */


    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = {Exception.class})
    public Result<String> delMerchant(Long merchantId) {
       int deleteCount= mapper.deleteByPrimaryKey(merchantId);
       if(deleteCount==0){
           return Result.createByErrorMessage("删除错误");
       }
       return Result.createBySuccessMessage("删除成功");

    }

    @Override
    public Result<Merchant> saveMerchant(Merchant merchant) {

        //校验店铺名有没有重复
        Merchant dbMerchant = selectByName(merchant.getName());
        if (dbMerchant != null) {
            return Result.createByErrorMessage("该店铺名已经被注册");
        }
        boolean result = isPiccBind(merchant);
        if (result) {
            return Result.createByErrorMessage("所选的人保商户已经被绑定");
        }
        Region region = regionMapper.selectByPrimaryKey(merchant.getRegionId());
        if (region != null) {
            merchant.setRegionName(region.getRegionName());
        }
        merchant.setPiccMid(0L);
        int insertCount = merchantMapper.insert(merchant);
        if (insertCount > 0) {
            return Result.createBySuccess(merchant);
        }
        return Result.createByErrorMessage("保存失败");
    }


    private boolean isPiccBind(Merchant merchant) {
        if(merchant.getPiccMid()!=null&&  merchant.getPiccMid()!=0){
            Example example = new Example(Merchant.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("piccMid", merchant.getPiccMid());
            List<Merchant> userList = selectByExample(example);
            if (userList.size() > 0 ) {
                Merchant merchant1=userList.get(0);
                if(merchant.getId()==null){
                    return true;
                }else  if(merchant1.getId()==merchant.getId()){
                    return false;
                }else {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public Result<Merchant> updateMerchant(Merchant merchant) {
        //校验店铺名有没有重复
        Merchant dbMerchant = selectByName(merchant.getName());

        if (dbMerchant != null && merchant.getId() != dbMerchant.getId()) {
            return Result.createByErrorMessage("该店铺名已经被注册");
        }
        boolean result = isPiccBind(merchant);
        if (result) {
            return Result.createByErrorMessage("所选的人保商户已经被绑定");
        }
        Region region = regionMapper.selectByPrimaryKey(merchant.getRegionId());
        if (region != null) {
            merchant.setRegionName(region.getRegionName());
        }

        int updateCount=updateNotNull(merchant);
        if (updateCount > 0) {
            return Result.createBySuccess(merchant);
        }
        return Result.createByErrorMessage("更新失败");

    }

	
	@Override
	public List<Merchant> selectByAgentId(String agentId) {
		Example example = new Example(Merchant.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("agentId", agentId);
		List<Merchant> merchantlist = merchantMapper.selectByExample(example);
		return merchantlist;
	}
}
